package com.vercon.moensmart.fragment.setting;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.vercon.common.Constants;
import com.vercon.common.utils.LogUtils;
import com.vercon.common.utils.MirrorDataStorage;
import com.vercon.common.wifi.EasyzcWifi;
import com.vercon.common.wifi.EasyzcWifiStateListener;
import com.vercon.moensmart.MainActivity;
import com.vercon.moensmart.R;
import com.vercon.moensmart.adapter.SettingWIFIRVAdapter;
import com.vercon.moensmart.adapter.base.BaseAdapter;
import com.vercon.moensmart.databinding.FragmentSettingWifiBinding;
import com.vercon.moensmart.dialog.HomeVolumeDialog;
import com.vercon.moensmart.dialog.WIFIConfirmDialog;
import com.vercon.moensmart.event.BaseEvent;
import com.vercon.moensmart.fragment.AppFragment;
import com.vercon.moensmart.fragment.base.BaseFragment;
import com.vercon.moensmart.fragment.manager.FragmentOpenManager;
import com.vercon.moensmart.popupwindow.RemoveWiFiWindow;
import com.vercon.moensmart.utils.ToastUtils;
import com.vercon.moensmart.viewmodel.SystemViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


public class WiFiFragment extends BaseFragment<FragmentSettingWifiBinding> implements EasyzcWifiStateListener, SettingWIFIRVAdapter.OnItemLongClickListener,
        BaseAdapter.BaseItemListener<ScanResult> {

    private final String TAG = getClass().getSimpleName();

    private SettingWIFIRVAdapter adapter;
    private WIFIConfirmDialog dialog;

    private String curConnectSSID = "";
    public static final String show_back = "show_iv_back";
    public static final String UpdateFirmware = "mIsUpdateFirmware";
    private int index = 1;//点击10次，打开设置页
    private long time;
    private boolean mShow_iv_back;
    private boolean mIsSetting = true;
    private boolean mIsUpdateFirmware = false;//是否是固件更新下载进来的
    SystemViewModel systemViewModel;
    @Override
    protected FragmentSettingWifiBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent) {
        return FragmentSettingWifiBinding.inflate(inflater,parent,false);
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        systemViewModel =  new ViewModelProvider(getActivity(),new ViewModelProvider.NewInstanceFactory()).get(SystemViewModel.class);
        adapter = new SettingWIFIRVAdapter(getContext());
        String token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"");
        if(TextUtils.isEmpty(token)){
            getBinding().tvUserExit.setVisibility(View.GONE);
        }

        getBinding().curWIFIRL.setVisibility(View.INVISIBLE);
        getBinding().wifiState.setVisibility(View.GONE);
        getBinding().wifiLV.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        getBinding().wifiLV.setAdapter(adapter);
        initWIFI();
    }

    @Override
    protected void initListener() {

        getBinding().tvVolumeSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HomeVolumeDialog volumeDialog = new HomeVolumeDialog();
                volumeDialog.show(getChildFragmentManager(),"");
            }
        });

        getBinding().tvUserExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //String token = MirrorDataStorage.instance().getString(Constants.STORAGE_KEY_TOKEN,"");
                //Fresco 清除缓存
                ImagePipeline imagePipeline = ImagePipelineFactory.getInstance().getImagePipeline();
                imagePipeline.clearMemoryCaches();
                imagePipeline.clearDiskCaches();
                imagePipeline.clearCaches();
                FragmentOpenManager.Companion.getInstance().closeFragment(getActivity());
                FragmentOpenManager.Companion.getInstance().hideFragment(getActivity(), AppFragment.class.getSimpleName());
                MirrorDataStorage.instance().storeString(Constants.STORAGE_KEY_TOKEN, "");
                systemViewModel.setUserTokenLiveData(null);
                FragmentOpenManager.Companion.getInstance().goToLoginFragment(getActivity());
            }
        });

        //wifi开关
        getBinding().onoffIV.setOnClickListener(this);
        getBinding().ivBack.setOnClickListener(this);
        getBinding().wifiStateIV.setOnClickListener(this);


        // wifi列表
        adapter.setItemOnClickListener(this);
        adapter.setOnItemLongClickListener(this);

        Bundle arguments = getArguments();
        if (arguments != null) {
            mShow_iv_back = arguments.getBoolean(show_back);
            mIsSetting = arguments.getBoolean(Constants.MoreApp, true);
            mIsUpdateFirmware = arguments.getBoolean(UpdateFirmware, false);
        }

        LogUtils.d("mIsSetting " + mIsSetting);


        getBinding().onoffIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchWifi();
            }
        });
//        getBinding().wifiStateIV.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (index >= 9) {
//                    index = 1;
//                    startActivity(new Intent(Settings.ACTION_SETTINGS));
//                    APPUtil.addPackageName("com.android.settings.Settings");
//                } else {
//                    index += 1;
//                }
//                time = System.currentTimeMillis();
//            }
//        });
        getBinding().ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentOpenManager.Companion.getInstance().closeFragment(getActivity());
            }
        });

    }

    private void initWIFI() {
        // wifi状态监听
        EasyzcWifi.Companion.get().addListener(this);
        // 按钮状态
        EasyzcWifi.Companion.get().refresh();
        refreshWifiStatus(EasyzcWifi.Companion.get().getWifiEnable());
        // FIXME: 2019/5/10 yzc 时间不能再缩短，导致已连接的wifi密码错误
        // 1.避免在调用scanWifi（）的短期内调用connect，就是避免在扫描期间调用connect
    }

    private void refreshWifiStatus(Boolean enable) {
        getBinding().wifiLV.setVisibility(enable ? View.VISIBLE : View.INVISIBLE);
        getBinding().onoffIV.setSelected(enable);
        getBinding().tvWifiCloseTip.setVisibility(enable ? View.INVISIBLE : View.VISIBLE);
        getBinding().selectNetWorkTV.setVisibility(enable ? View.VISIBLE : View.INVISIBLE);
        getBinding().pbWifi.setVisibility(enable ? View.VISIBLE : View.INVISIBLE);

    }

    private void NotifiyData(@NotNull List<ScanResult> list) {
            if ( getBinding().pbWifi != null) {
                getBinding().pbWifi.setVisibility(View.GONE);
            }
            if (getBinding().wifiLV != null) {
                if (getBinding().wifiLV.isComputingLayout()) {
                    if (getBinding().pbWifi != null) {
                        getBinding().pbWifi.setVisibility(View.VISIBLE);
                    }
                    NotifiyData(list);
                } else {
                    adapter.setData(list);
                }
            }
    }
    /**
     * 去除同名WIFI
     */
    private  List<ScanResult> noSameName(List<ScanResult> oldSr) {
        List<ScanResult> newSr = new ArrayList<>();
        for (ScanResult result : oldSr) {
            if (!TextUtils.isEmpty(result.SSID) && !containName(newSr, result.SSID)) {
                newSr.add(result);
            }
        }
        return newSr;
    }

    /**
     * 判断一个扫描结果中，是否包含了某个名称的WIFI
     */
    private  boolean containName(List<ScanResult> sr, String name) {
        for (ScanResult result : sr) {
            if (!TextUtils.isEmpty(result.SSID) && result.SSID.equals(name)) {
                return true;
            }
        }

        return false;
    }
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void updateDate(BaseEvent event) {
        if (event.getType().equals(Constants.refreshWifi)) {
            refreshWifiStatus(EasyzcWifi.Companion.get().getEnable());
            EasyzcWifi.Companion.get().refresh();
        }
    }


    @Override
    public void onDestroyView() {
        EasyzcWifi.Companion.get().removeListener(this);
        EventBus.getDefault().unregister(this);
        super.onDestroyView();

    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onConnecting() {
        LogUtils.d(TAG, "onConnecting ");
        getBinding().wifiStateIV.setImageResource(getResId(0));
        if (null != getBinding().wifiState && EasyzcWifi.Companion.get().getWifiEnable()) {
            getBinding().wifiState.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onNetWorkStateChanged() {
        LogUtils.d(TAG, "onNetWorkStateChanged ");
    }

    @Override
    public void onWiFiStateChanged() {
        LogUtils.d(TAG, "onWiFiStateChanged ");
    }

    @Override
    public void onConnectFault() {

        LogUtils.d(TAG, "onConnectFault ");
        getBinding().curWIFIRL.setVisibility(View.INVISIBLE);
        getBinding().nameTV.setText("");
        getBinding().wifiStateIV.setImageResource(getResId(0));
        getBinding().wifiState.setVisibility(View.GONE);
        ToastUtils.Companion.showToast(getString(R.string.wifi_password_error));
    }
    @Override
    public void onDisconnected() {
        getBinding().curWIFIRL.setVisibility(View.INVISIBLE);
        getBinding().nameTV.setText("");
        getBinding().wifiStateIV.setImageResource(getResId(0));
        getBinding().wifiState.setVisibility(View.GONE);
    }
    @Override
    public void onConnectSuccess(ScanResult scanResult) {
        LogUtils.d(TAG, "onConnectSuccess scanResult:" + scanResult);
        try{
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getBinding().wifiState.setVisibility(View.GONE);
                    if (null != scanResult) {
                        getBinding().nameTV.setText(scanResult.SSID);
                        //判断网络是否可用
                        getBinding().wifiStateIV.setImageResource(getResId(WifiManager.calculateSignalLevel(scanResult.level, 100)));
                        if (isNetSystemUsable(getActivity())) {
                            getBinding().wifiNoNet.setVisibility(View.INVISIBLE);
                        } else {
                            getBinding().wifiNoNet.setVisibility(View.VISIBLE);
                        }
                    } else {
                        getBinding().nameTV.setText("");
                        getBinding().wifiStateIV.setImageResource(getResId(0));
                    }
                    getBinding().curWIFIRL.setVisibility(View.VISIBLE);
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 判断网络是否可用
     *
     * @return
     */
    public static boolean isNetSystemUsable(FragmentActivity activity) {
        boolean isNetUsable = false;
        if (activity == null) {
            return false;
        }
        ConnectivityManager manager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                NetworkCapabilities networkCapabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
                if (networkCapabilities != null) {
                    isNetUsable = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return isNetUsable;
    }

    @Override
    public void onScaning() {
        LogUtils.d(TAG, "onScaning");
        if (EasyzcWifi.Companion.get().getEnable()) {
            if (getBinding().pbWifi == null) return;
            getBinding().pbWifi.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onScanResult(@NotNull List<ScanResult> list) {
        LogUtils.i(TAG, "onScanResult " + list.size() );
        try{
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                        getBinding().wifiState.setVisibility(View.GONE);
                        List<ScanResult> scanResults = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            if (!list.get(i).SSID.equals("")) {
                                scanResults.add(list.get(i));
                            }
                        }
                        LogUtils.i(TAG, "onScanResult " + list.size() + "  " + scanResults.size());
                        scanResults = noSameName(scanResults);
                        NotifiyData(scanResults);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private  long lastClickTime = 0;
    private  final int CLICK_TIME = 2000; //快速点击间隔时间

    // 判断按钮是否快速点击
    private  boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < CLICK_TIME) {//判断系统时间差是否小于点击间隔时间
            return true;
        }
        lastClickTime = time;
        return false;
    }
    private int getResId(int level) {
        if (level <= 0) {
            return R.drawable.ic_wifi_level_new_1;
        } else if (level <= 50) {
            return R.drawable.ic_wifi_level_new_11;
        } else if (level <= 70) {
            return R.drawable.ic_wifi_level_new_2;
        } else if (level <= 90) {
            return R.drawable.ic_wifi_level_new_3;
        } else if (level <= 100) {
            return R.drawable.ic_wifi_level_new_4;
        }
        return R.drawable.ic_wifi_level_new_not;
    }

    @Override
    public void onItemLongClick(ScanResult result, View view) {
        //长按WiFi列表取消保存
        RemoveWiFiWindow wiFiWindow = new RemoveWiFiWindow(getContext());
        wiFiWindow.setOnRemoveListener(() -> {
            //取消保存，刷新列表
            boolean b = EasyzcWifi.Companion.get().removeWifi(getContext(), result);
            if (b) {
                EasyzcWifi.Companion.get().refresh();
            }
        });
        wiFiWindow.show(view);
    }

    @Override
    public void onItemClickListener(@Nullable View v, ScanResult scanResult, int position) {
        //点击WiFi列表
        curConnectSSID = scanResult.SSID;
//        nameTV.setText("");
//        wifiStateIV.setImageResource(getResId(0));
        EasyzcWifi.Companion.get().preConnect(scanResult, () -> {
            // 当前wifi需要输入密码
            dialog = new WIFIConfirmDialog();
            dialog.setWIFIName(curConnectSSID);
            dialog.setOnConfirmListener(new WIFIConfirmDialog.OnConfirmListener() {
                @Override
                public void onYse(String ssid, String password) {
                    dialog.dismiss();
                    if (password.length() >= 8) {
                        // 连接
                        EasyzcWifi.Companion.get().passwordConnect(ssid, password);
                    }
                }

                @Override
                public void onNo() {
                    dialog.dismiss();
                }
            });
            dialog.show(getChildFragmentManager(), "WIFIConfirmDialog");
            return null;
        });
    }

    @Override
    public void onClick(View v) {


    }

    private void switchWifi() {
        EasyzcWifi.Companion.get().turn(enable -> {
            LogUtils.i(TAG, " wifi开关: " + enable);
            getBinding().onoffIV.setSelected(enable);
            if (enable) {
                getBinding().selectNetWorkTV.setVisibility(View.VISIBLE);
                getBinding().pbWifi.setVisibility(View.VISIBLE);
                getBinding().wifiLV.setVisibility(View.VISIBLE);
                getBinding().tvWifiCloseTip.setVisibility(View.INVISIBLE);
            } else {
                getBinding().tvWifiCloseTip.setVisibility(View.VISIBLE);
                getBinding().wifiStateIV.setImageResource(getResId(0));
                getBinding().selectNetWorkTV.setVisibility(View.INVISIBLE);
                getBinding().pbWifi.setVisibility(View.GONE);
                getBinding().curWIFIRL.setVisibility(View.INVISIBLE);
                getBinding().wifiLV.setVisibility(View.INVISIBLE);
                getBinding().wifiState.setVisibility(View.GONE);
            }
            return null;
        });
    }



}
